package com.ant.sha1.utils;

import com.alibaba.fastjson.JSON;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * Created by baichuan on 2016/12/8.
 */
public class MD5Utils {

    private static final char[] chars = {'0','a', 'b', 'c', 'd', 'e', 'f', '1', '2', '3', '4', '5', '6', '7', '8', '9',};

    public static String encode(byte[] source) {
        if (source == null)
            return null;
        MessageDigest digest = null;
        try {
            digest = MessageDigest.getInstance("MD5");
            digest.update(source);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        byte[] data = digest.digest();
        System.out.println(JSON.toJSON(data));
        char[] respon = new char[32];
        int k = 0;
        for (int i = 0, m = data.length; i < m; i++) {

            respon[k++] = chars[data[i] >>> 4 & 0xf];
            respon[k++] = chars[data[i] & 0xf];
        }

        return new String(respon);
    }

    public static String encode(String source) {
        return (source == null || "".equals(source)) ? "" : encode(source.getBytes());
    }
}
